import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'dart:io';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logger/logger.dart';
import 'package:merchants/providers/settings_provider.dart';
import 'package:flutter/foundation.dart';

class _PrettyDioLogger extends Interceptor {
  final _logger = Logger();

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _logger.i('➡️  [${options.method}] ${options.uri}');
    _logger.i('Headers: ${options.headers}');
    _logger.i('Query : ${options.queryParameters}');
    _logger.i('Body   : ${options.data}');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _logger.i('✅  [${response.statusCode}] ${response.requestOptions.uri}');
    _logger.i('Response: ${response.data}');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    _logger.e('❌  [Error] ${err.requestOptions.uri} -> ${err.message}');
    super.onError(err, handler);
  }
}

// Riverpod Provider：任何地方 ref.read(dioProvider) 即可拿到同一个 Dio
final dioProvider = Provider<Dio>((ref) {
  final settingsAsync = ref.watch(settingsProvider);

  // 若设置尚未加载，则抛异常；调用方可捕获或显示加载动画
  final settings = settingsAsync.maybeWhen(
    data: (s) => s,
    orElse: () => null,
  );

  if (settings == null) {
    throw Exception('Settings 未加载，无法创建 Dio');
  }

  final baseUrl = settings.baseUrl;

  final dio = Dio(
    BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 8),
      receiveTimeout: const Duration(seconds: 8),
      responseType: ResponseType.json,
    ),
  );

  // 日志／错误拦截器
  dio.interceptors.add(_PrettyDioLogger());

  return dio;
});
